from py3db.mysql import MySql
from config.db import DB_CONFIG
from config.app import APP_CODE
import re
from bs4 import BeautifulSoup
SOURCE = "game"
CONTENT = "game_content"


class MdChange:
    def __init__(self):
        self.db = MySql(DB_CONFIG['host'], DB_CONFIG['user'], DB_CONFIG['password'], APP_CODE)
        with open(f"../md/{SOURCE}.md", "w", encoding="utf-8") as fp:
            fp.write("## 图片\n")

    def get_data_list(self, limit):
        sql = f"select * from {SOURCE} where {CONTENT} is not null"
        results = self.db.query(sql)[0:limit]
        for each in results:
            yield each

    def write_md(self, limit=10):
        for result in self.get_data_list(limit):
            _, title, content, *_ = result
            with open(f"../md/{SOURCE}.md", "a", encoding="utf-8") as fp:
                fp.write(f"### {title}\n")
                fp.write(f"{content}\n")

    def write_html(self, limit=10):
        for result in self.get_data_list(limit):
            _, title, content, *_ = result
            file_name = re.sub('[\/:*?"<>|]', '-', title) + ".html"
            html_frame = f'''
                <html>
                    <head>
                       <meta http-equiv="content-type" content="text/html; charset=utf-8" />
                    </head>
                    <body>
                        {content}
                    </body>
                </html>
        '''
            soup = BeautifulSoup(html_frame, "lxml")
            [s.extract() for s in soup.findAll(name="div", attrs={"class" :"tiptop"})]
            [s.extract() for s in soup.findAll(name="div", attrs={"class": "apd"})]
            with open(f"../html/{file_name}", "w", encoding="utf-8") as fp:
                fp.write(str(soup))


if __name__ == '__main__':
    md = MdChange()
    md.write_html(100)
